import koaBody from "koa-body"
import { useKoa, useNode } from "@/hooks"
import dotenv from "dotenv"

dotenv.config({ path: ".env.local" })

const { child_process } = useNode()

const { createRouter } = useKoa()

const router = createRouter()

router.post("/push", koaBody(), (ctx, next) => {
  console.log("代码push了")
  const { hook_name, project, password } = ctx.request.body

  const { default_branch, description } = project

  const isOk =
    password == process.env.password &&
    description == "puppeteer_automatic" &&
    hook_name == "push_hooks" &&
    default_branch == "master"

  if (isOk) {
    const command = {
      pull: "pnpm pull",
      build: "pnpm build",
      buildWeb: "pnpm build:web",
      buildMain: "pnpm build:main",
      restartAll: "pm2 delete all && pm2 start ecosystem.config.js",
    }

    // child_process.execSync(command.pull)
    // child_process.execSync(command.build)

    console.log("打包：web")
    child_process.execSync(command.buildWeb)

    console.log("打包：main")
    child_process.execSync(command.buildMain)

    console.log("pm2：restart all")
    child_process.execSync(command.restartAll)
  }

  ctx.body = "push"
  next()
})

export default router.routes()
